package com.zzy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzy.dao.UserDao;
import com.zzy.model.User;
import com.zzy.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    public List<User> findAll(){
        return userDao.findAll();
    }

    public List<User> findByName(String name){
        return userDao.findByName(name);
    }

    public List<User> findList(User user){
        return userDao.findList(user);
    }

    public Integer saveUser(User user){
        int i = userDao.saveUser(user);// 执行成功的条数
        System.out.println(user.getId());//这里能获取到 保存后 返回的 ID
        return i;
    }

    @Cacheable("users")
    public User findOne(Integer id){
        return userDao.findOne( id);
    }

    @Override
    public User findModelByParam(User user) {
        if(user==null){
            user = new User();//保证不报错
        }
        User user1 = userDao.findModelByParam( user);
        if(user1==null){
            user1 = new User();
        }
        return user1;
    }

    public Integer deletes(Integer id){
        return userDao.deletes(id);
    }
    public Integer update(User user){
        return userDao.update(user);
    }

    public PageInfo<User> findByPage(User user){
        if (user==null){
            user = new User();
            user.setPageCount(1);
            user.setPageSize(10);
        }
        if(user.getPageCount()==null){
            user.setPageCount(1);
        }
        if(user.getPageSize()==null){
            user.setPageSize(1);
        }
        PageHelper.startPage(user.getPageCount(),user.getPageSize());
        List<User> users = userDao.findByPage(user);

        for(User u : users){
            if(u.getStatus().equals(0)){
                u.setFlag(false);
            }
            if(u.getStatus().equals(1)){
                u.setFlag(true);
            }
        }

        return new PageInfo<User>(users);
    }
}
